import { fileURLToPath, URL } from "node:url";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import dayjs from 'dayjs'
import obfuscatorPlugin from 'rollup-plugin-obfuscator';
import legacy from '@vitejs/plugin-legacy'
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import VueSetupExtend from "vite-plugin-vue-setup-extend";

// 生成版本号
const version = dayjs().format('YYYYMMDDHHmmss')

// 优化后的插件：给 HTML 中的所有资源添加版本号
const addVersion = () => ({
  name: 'vite-plugin-add-version',
  apply: 'build',
  enforce: 'post',
  transformIndexHtml: (html) => {
    let processedHtml = html.replace(
      // 只匹配 src/href 属性中的资源，避免影响其他内容
      /(src|href)=["']([^"']*?)(\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|\.webp|\.svg)(?=["'])/g,
      `$1="$2$3?v=${version}"`,
    );
    // 处理 data-src 属性
    processedHtml = processedHtml.replace(
      /data-src=["']([^"']*?)\.js(["'])/g,
      `data-src="$1.js?v=${version}"$2`,
    );
    return processedHtml;
  },
  generateBundle(options, bundle) {
    Object.keys(bundle).forEach((fileName) => {
      if (fileName.endsWith('.html')) {
        let htmlContent = bundle[fileName].source.toString();
        htmlContent = htmlContent.replace(
          /(src|href)=["']([^"']*?)(\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|\.webp|\.svg)(?=["'])/g,
          `$1="$2$3?v=${version}"`,
        );
        htmlContent = htmlContent.replace(
          /data-src=["']([^"']*?)\.js(["'])/g,
          `data-src="$1.js?v=${version}"$2`,
        );
        bundle[fileName].source = htmlContent;
      }
    });
  },
});

// 优化后的插件：给 CSS 中的图片 URL 添加版本号
const addVersionForCss = () => ({
  name: 'vite-plugin-css-url-version',
  enforce: 'post',
  generateBundle(options, bundle) {
    Object.keys(bundle).forEach((fileName) => {
      const file = bundle[fileName];
      if (fileName.endsWith('.css')) {
        let content = file.type === 'asset' ? file.source.toString() : file.code;
        // 只匹配 CSS 中的 url() 引用
        content = content.replace(
          /url\(["']?([^"')]+?)(\.png|\.jpg|\.jpeg|\.gif|\.webp|\.svg)["']?\)/g,
          `url("$1$2?v=${version}")`,
        );
        if (file.type === 'asset') {
          file.source = content;
        } else {
          file.code = content;
        }
      }
    });
  },
});


export default defineConfig(({ mode }) => {
  console.log('VITE_MODE:',mode)
  const env = loadEnv(mode, process.cwd(), "");

  return {
    plugins: [
      vue(),
      legacy({
        targets: ['chrome >= 52', 'safari >= 11', 'edge >= 18', 'firefox >= 60'],
        renderLegacyChunks: true,
        modernPolyfills: true,
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
      }),
     
      VueSetupExtend(),
      AutoImport({ resolvers: [ElementPlusResolver()] }),
      Components({ resolvers: [ElementPlusResolver()] }),
      addVersionForCss(),
       addVersion(),
    ],
    // 简化CSS配置，使用postcss.config.js文件
    css: {
      postcss: './postcss.config.js'
    },
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    server: {
      port: parseInt(env.VITE_PORT) || 3001,
      open: env.VITE_OPEN_BROWSER === "true",
      proxy: {
        "/user": {
          target: "http://localhost:3000",
          changeOrigin: true,
         // rewrite: (path) => path.replace(/^\/user/, ""),
        },
        "/wechat": {
          target: "http://localhost:3000",
          changeOrigin: true,
         // rewrite: (path) => path.replace(/^\/user/, ""),
        },
        "/proxy": {
          target: "http://localhost:3000/proxy", // api接口代理,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/proxy/, ""),
        },
        "/upload": {
          target: "http://localhost:3000",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/upload/, ""),
        },
        "/socket.io": {
          target: "ws://localhost:5174",
          ws: true,
        },
      },
    },
    base: env.VITE_MODE === "production" ? "./" : "./",
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      manifest: false,
      sourcemap: false,
      minify: 'terser',
      chunkSizeWarningLimit: 100,
      cssCodeSplit: true,
      target: 'es2015',
      rollupOptions: {
        plugins: [
          // 混淆插件（仅在生产环境启用）
          obfuscatorPlugin({
            // javascript-obfuscator 配置选项
            options: {
              compact: true, // 压缩代码
              controlFlowFlattening: true, // 混淆控制流，降低代码可读性
              controlFlowFlatteningThreshold: 0.58, // 控制流扁平化阈值
              stringArray: true, // 混淆字符串
              stringArrayEncoding: ['base64'], // 字符串混淆编码
              deadCodeInjection: true,// 注入无用代码，增加混淆度
              deadCodeInjectionThreshold: 0.28,// 无用代码注入阈值
            },
            // 排除第三方库（可选）
            exclude: [/node_modules/]
          })
        ],
        output: {
          manualChunks: (id) => {
            if (id.includes('node_modules')) {
              const packageName = id.toString().split('node_modules/')[1]?.split('/')[0]
              return packageName || 'vendor'
            }
            return 'common'
          },
          entryFileNames: `assets/js/[name].js`,
          chunkFileNames: `assets/js/[name].js`,
          assetFileNames: `assets/[ext]/[name].[ext]`,
        },
      },
      terserOptions: {
        compress: {
          drop_console: env.VITE_DROP_CONSOLE === "true",
          drop_debugger: env.VITE_DROP_DEBUGGER === "true",
          // pure_funcs: ['console.log', 'console.debug', 'console.warn', 'console.error']
        },
        output: {
          comments: false,
        },
      },
    },
  };
});
